<script setup lang="ts">
import { addAreaAPI, deleteAreaAPI, editAreaAPI, getAreaDataAPI, getRuleDropListAPI } from '@/apis/carArea';
import type { AddAreaParamsType, AreaItemType, RuleDropListType } from '@/types/carArea';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';

// 获取列表参数
const getAreaParams = ref<{page: number; pageSize: number}>({
  page: 1,
  pageSize: 5
})

// 获取列表
const areaList = ref<AreaItemType[]>([]) // 列表数据
const total = ref<number>(0) // 数据总条数
const getAreaData = async () => {
  const res = await getAreaDataAPI(getAreaParams.value)
  areaList.value = res.data.rows
  total.value = res.data.total
}
getAreaData()

// 弹窗 添加/编辑 --------------
const dialogVisible = ref<boolean>(false) // 弹窗控制
const formRef = ref<FormInstance>() // 表单实例
const areaId = ref<number | undefined>() // 区域id

// 获取关联计费规则下拉列表
const ruleDropList = ref<RuleDropListType[]>([])
const getRuleDropList = async () => {
  const res = await getRuleDropListAPI()
  ruleDropList.value = res.data
}

// 开启弹窗
const openDialog = async (row?: AreaItemType) => {
  await getRuleDropList() // 获取关联计费规则下拉列表

  // 编辑回显
  if (row) {
    areaId.value = row.id
    addAreaParams.value.areaName = row.areaName, // 区域名称
    addAreaParams.value.areaProportion = String(row.areaProportion), // 区域面积
    addAreaParams.value.remark = row.remark, // 备注
    addAreaParams.value.ruleId = row.ruleId, // 关联计费规则
    addAreaParams.value.spaceNumber = String(row.spaceNumber) // 车位数
  }

  dialogVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  
  addAreaParams.value = {
    areaName: '', // 区域名称
    areaProportion: '', // 区域面积
    remark: '', // 备注
    ruleId: undefined, // 计费规则id
    spaceNumber: '' // 车位数量
  }
  formRef.value?.resetFields()
  areaId.value = undefined
}

// 表单参数
const addAreaParams = ref<AddAreaParamsType>({
  areaName: '', // 区域名称
  areaProportion: '', // 区域面积
  remark: '', // 备注
  ruleId: undefined, // 计费规则id
  spaceNumber: '' // 车位数量
})

// 表单校验规则
const addAreaRules = ref<FormRules<AddAreaParamsType>>({
  areaName: [
    { required: true, message: '请输入区域名称', trigger: 'blur' }
  ],
  areaProportion: [
    { required: true, message: '请输入区域面积', trigger: 'blur' },
    { pattern: /^[0-9{.}]*$/, message: '请输入正数', trigger: 'blur' }
  ],
  ruleId: [
    { required: true, message: '请选择计费规则', trigger: 'blur' }
  ],
  spaceNumber: [
    { required: true, message: '请输入车位数量', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '请输入正整数', trigger: 'blur' }
  ]
})

// 添加/编辑  区域
const loadingFlag = ref(false)
const addArea = async () => {
  await formRef.value!.validate()
  loadingFlag.value = true
  try {
    if (!areaId.value) {
      // 添加
      await addAreaAPI(addAreaParams.value)
      ElMessage.success('添加成功')
    } else {
      // 编辑
      const res = await editAreaAPI({
        ...addAreaParams.value,
        id: areaId.value!
      })
      if (res.code === 10000) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
  } finally {
    loadingFlag.value = false
  }
  getAreaData() // 刷新表格数据
  closeDialog() // 关闭弹窗
}

// 删除区域
const deleteArea = async (id: string) => {
  await ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  const res = await deleteAreaAPI(id)

  if (res.code === 10000) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }

  getAreaData() // 刷新表格数据
  closeDialog() // 关闭弹窗
}

// 下拉框重新校验
const validateSelect = () => {
  formRef.value?.validateField('ruleId')
}

</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="openDialog()" v-permission="'parking:area:add_edit'">添加区域</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="areaList">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="区域名称" prop="areaName" />
        <el-table-column label="车位数(个)" prop="spaceNumber" />
        <el-table-column label="面积(m²)" prop="areaProportion" />
        <el-table-column label="计费规则" prop="ruleName" />
        <el-table-column label="备注">
          <template #default="{ row }">
            {{ row.remark || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openDialog(row)" v-permission="'parking:area:add_edit'">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteArea(row.id)" v-permission="'parking:area:remove'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :total="total"
        :page-sizes="[2,5,10,20]"
        v-model:current-page="getAreaParams.page" 
        v-model:page-size="getAreaParams.pageSize"
        @change="getAreaData()"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog @close="closeDialog()" v-model="dialogVisible" :title="!areaId ? '添加区域' : '编辑区域'" width="580px">
      <div class="form-container">
        <el-form ref="formRef" label-position="top" :model="addAreaParams" :rules="addAreaRules">
          <el-form-item label="区域名称" prop="areaName">
            <el-input v-model="addAreaParams.areaName" placeholder="请输入区域名称"></el-input>
          </el-form-item>
          <el-form-item label="车位数(个)" prop="spaceNumber">
            <el-input type="number" v-model="addAreaParams.spaceNumber" placeholder="请输入车位个数"></el-input>
          </el-form-item>
          <el-form-item label="面积(m²)" prop="areaProportion">
            <el-input v-model="addAreaParams.areaProportion" placeholder="请输入面积"></el-input>
          </el-form-item>
          <el-form-item label="关联计费规则" prop="ruleId">
            <el-select @change="validateSelect" v-model="addAreaParams.ruleId" placeholder="请选择">
              <el-option
                v-for="item in ruleDropList"
                :key="item.ruleId"
                :label="item.ruleName"
                :value="item.ruleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="addAreaParams.remark"
              :rows="2"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="addArea()" :loading="loadingFlag">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.radio-group {
  width: 100%;
  .radio-group-list {
    width: 100%;
    display: flex;
    .el-radio {
      padding: 10px;
    }
  }
}

.billing-rules {
  display: flex;
  gap: 10px;
}

.partition-content {
  display: flex;
  justify-content: space-between;
  .el-input {
    width: 109px;
    margin: 0 10px;
  }
  &:nth-child(1) {
    margin-bottom: 15px;
  }
}

.mianfei-timer {
  display: flex;
  align-items: end;
  .el-input {
    width: 160px;
    margin-left: 7px
  }
}

.rule-container {
  padding: 20px;
  background-color: #fff;
}

.rules .el-form-item {
  padding: 0 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
